<template>
  <c-card isAffix>
    <c-table
      row-key="_id"
      class="table-template__table"
      :loading="loading"
      :data="tableData"
      v-model:search="searchParams"
      @refresh="queryTableData"
    >
      <!-- 搜索栏 -->
      <!-- <template #search>
        <c-input v-model="searchParams.userid" placeholder="请输入userid" />
      </template> -->

      <!-- 操作栏 -->
      <template #handle="{}">
        <el-button type="primary" @click="hanleModal">添加分享卡</el-button>
      </template>

      <!-- 表格 -->
      <template #table>
        <el-table-column label="排序" width="60" align="center">
          <template #default>
            <img class="table-drag-img" src="@/assets/common/drag.svg" />
          </template>
        </el-table-column>
        <el-table-column prop="share_imgs" label="分享卡图片" width="120">
          <template #default="{ row }">
            <el-image
              class="share-img"
              :src="row.share_imgs[0]"
              :preview-src-list="row.share_imgs"
              preview-teleported
              hide-on-click-modal
              fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column prop="share_title" label="分享标题" />
        <el-table-column prop="share_path" label="分享标题" />
        <el-table-column prop="share_title" label="关联图像类型">
          <template #default="{ row }">
            {{ row.image_info.text }}
          </template>
        </el-table-column>
        <el-table-column prop="share_title" label="关联图像分组类型">
          <template #default="{ row }">
            {{ row.images_group_info.name }}
          </template>
        </el-table-column>

        <el-table-column label="状态">
          <template #default="{ row }">
            <c-switch
              v-model="row.status"
              :activeValue="0"
              :inactiveValue="1"
              :before-change="() => switchBeforeChange(row)"
              @refresh="queryTableData"
            ></c-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间">
          <template #default="{ row }">
            {{ dayjs(row.create_time).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button text type="primary" @click="hanleEditModal(row)">编辑</el-button>
            <el-button type="danger" text @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </template>
    </c-table>

    <!-- 弹窗 -->
    <c-dialog title="添加分享卡" :width="1000" name="add-share-card-popup">
      <add-share-card-popup @refresh="queryTableData"></add-share-card-popup>
    </c-dialog>
  </c-card>
</template>

<script setup name="share-card-list">
import { ref, computed, onMounted } from 'vue';

// hooks
import { useTable } from '@/hooks/useTable/index.js';
import { useFetch } from '@/hooks/useFetch/index.js';

// components
import { MessageBox } from '@/utils/message-box';
import { ElMessage } from 'element-plus';
import Sortable from 'sortablejs';
import AddShareCardPopup from './components/add-share-card-popup.vue';

// router
import { useRouter } from 'vue-router';
const router = useRouter();

// store modal
import { useModalStore } from '@/pinia/modules/modal';
const modalStore = useModalStore();

// user
import { useUserStore } from '@/pinia/modules/user.js';
const userStore = useUserStore();

import { pageListUserLog } from '@/apis/user';
import {
  listShareCard,
  setShareCardStatus,
  delShareCard,
  setShareCardWeight,
} from '@/apis/share-card.js';

import { UserPlatform } from '@/config/global-variable';

import dayjs from 'dayjs';

// 表格相关
const { loading, paging, searchParams, tableData, queryTableData, delTableRow } = useTable({
  api: listShareCard,
  params: {
    uni_platform: '',
    userid: '',
  },
  options: {},
  callBack: () => {},
});

const hanleModal = () => {
  modalStore.openModal('add-share-card-popup');
};

const hanleEditModal = (row) => {
  modalStore.openModal('add-share-card-popup', row);
};

// 状态开关
const switchBeforeChange = async (row) => {
  return await setShareCardStatus({ _id: row._id, status: row.status == 1 ? 0 : 1 }).catch(
    (err) => err,
  );
};

// 删除
const handleDelete = (row) => {
  delTableRow({
    api: delShareCard,
    params: { _id: row._id },
  });
};

// 行拖拽
const rowDrop = () => {
  const tbody = document.querySelector('.table-template__table tbody');
  Sortable.create(tbody, {
    group: {
      name: 'shared',
      pull: true,
      put: true,
    },
    handle: '.table-drag-img',
    animation: 150,
    async onEnd({ newIndex, oldIndex }) {
      console.log(newIndex, oldIndex, 'newIndex, oldIndex');

      const currRow = tableData.value.splice(oldIndex, 1)[0];

      tableData.value.splice(newIndex, 0, currRow);

      let allList = [];
      for (let index = 0; index < tableData.value.length; index++) {
        const item = tableData.value[index];
        console.log(item, index, 'index');

        allList.push(setShareCardWeight({ _id: item._id, weight: index }));
      }

      loading.value = true;
      await Promise.all(allList);
      loading.value = false;

      queryTableData();
    },
  });
};

onMounted(() => {
  rowDrop();
});
</script>

<style lang="scss" scoped>
.share-img {
  width: 80px;
  height: auto;
  aspect-ratio: 5/4;
}
</style>
